'use client';
import './globals.css';
import { AntdRegistry } from '@ant-design/nextjs-registry';
import BasicLayout from '@/layouts/BasicLayout';
import React, { useCallback, useEffect } from 'react';
import { Provider, useDispatch } from 'react-redux';
import store, { AppDispatch } from '@/store';
import { setLoginUser } from '@/store/loginUser';
import PermLayout from '@/permission/PermLayout';
import { getLoginUserInfoUsingPost } from '@/api/UserApi';

/**
 * 全局初始化
 * @param children
 * @constructor
 */
const InitLayout: React.FC<
  Readonly<{
    children: React.ReactNode;
  }>
> = ({ children }) => {
  // 使用Callback缓存函数
  const dispatch = useDispatch<AppDispatch>();
  const initLoginUser = useCallback(async () => {
    const res = await getLoginUserInfoUsingPost();
    if (res.data) {
      dispatch(setLoginUser(res.data));
    } else {
    }
  }, []);
  // 只执行一次init
  useEffect(() => {
    initLoginUser().then(() => {});
  }, []);
  return children;
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="zh">
      <body>
        <AntdRegistry>
          <Provider store={store}>
            <InitLayout>
              <BasicLayout>
                <PermLayout>{children}</PermLayout>
              </BasicLayout>
            </InitLayout>
          </Provider>
        </AntdRegistry>
      </body>
    </html>
  );
}
